package com.example.microservices.inventory.service.impl;

import com.example.microservices.inventory.model.Product;
import com.example.microservices.inventory.repository.ProductRepository;
import com.example.microservices.inventory.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {

    private final ProductRepository productRepository;

    @Override
    public List<Product> findAllProducts() {
        return productRepository.findAll();
    }

    @Override
    public Product findProductById(Long id) {
        return productRepository.findById(id);
    }

    @Override
    @Transactional
    public Product createProduct(Product product) {
        productRepository.save(product);
        return product;
    }

    @Override
    @Transactional
    public Product updateProduct(Long id, Product product) {
        Product existingProduct = productRepository.findById(id);
        if (existingProduct == null) {
            throw new RuntimeException("Product not found with id: " + id);
        }
        product.setId(id);
        productRepository.update(product);
        return product;
    }

    @Override
    @Transactional
    public void deleteProduct(Long id) {
        Product existingProduct = productRepository.findById(id);
        if (existingProduct == null) {
            throw new RuntimeException("Product not found with id: " + id);
        }
        productRepository.deleteById(id);
    }

    @Override
    @Transactional
    public void updateProductStock(Long id, Integer quantity) {
        Product product = productRepository.findById(id);
        if (product == null) {
            throw new RuntimeException("Product not found with id: " + id);
        }
        if (product.getStock() + quantity < 0) {
            throw new RuntimeException("Insufficient stock for product: " + id);
        }
        productRepository.updateStock(id, product.getStock() + quantity);
    }
} 